
Imports System
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO


Namespace _2bMatesSite
	''' <summary>
	''' Summary description for see_all_friends.
	''' </summary>
	Public Partial Class see_all_friends
		Inherits BaseWebPage

		Protected lblInterests As System.Web.UI.WebControls.Label
		Protected Literal1 As System.Web.UI.WebControls.Literal
		Protected blankImagesCount As Integer = 0
		Protected currentPageNumber As Integer = 0
		Protected firstPageNumber As Integer = 0
		' the first page of page links
		Protected lastPageNumber As Integer = 0
		Protected pagesRest As Integer = 0
		Protected action As String = "0"
		Protected usrID As Integer = -1

		Protected sSortBy As String = Constants.FRIENDS_SORT_BY_NAME

		Protected htPageConstants As New Hashtable()

		Public Function CreateDataSource() As ICollection

			Dim usr As BO.User = Users.GetUserByID(usrID)

			Dim startIndex As Integer = Convert.ToInt32(txtStartIndexHidden.Text)
			Dim endIndex As Integer = startIndex + Constants.MAX_PICTURES_ON_PAGE

			Dim dt As New DataTable()
			Dim dr As DataRow

			dt.Columns.Add(New DataColumn("ImageURL", GetType(String)))
			dt.Columns.Add(New DataColumn("Name", GetType(String)))
			dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
			dt.Columns.Add(New DataColumn("DelFriendVisibility", GetType(Boolean)))
			dt.Columns.Add(New DataColumn("FriendID", GetType(String)))
			dt.Columns.Add(New DataColumn("FriendItemURL", GetType(String)))
			dt.Columns.Add(New DataColumn("DeleteCommand", GetType(String)))
			' added for sorting
			dt.Columns.Add(New DataColumn("Gender", GetType(Integer)))
			dt.Columns.Add(New DataColumn("Date", GetType(Date)))
			dt.Columns.Add(New DataColumn("IsOnline", GetType(Integer)))
			dt.Columns.Add(New DataColumn("Age", GetType(Date)))

			dt.Columns.Add(New DataColumn("FullName", GetType(String)))
			dt.Columns.Add(New DataColumn("SortOrder", GetType(Integer)))

			Dim tmpUserPic As UserPicture = Nothing

			Dim ufList As UsersFriends = usr.DirectFriends
			'ArrayList ufList = (ArrayList)usr.DirectFriends.GetList();
			Dim usrDFWithMazFirst As New ArrayList()
			Dim FriendsCount As Integer = ufList.Count
			Dim imagesOnLastRow As Integer = 0
			Dim t As Integer = 0
			Dim counter As Integer = 0

			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			' init friends without Maz
			For Each udf As DirectFriend In ufList
				If LoggedUsersList.Contains(udf.[Friend].ID) Then
					udf.IsOnline = Constants.ONLINE_STAUS_ON
				End If
				usrDFWithMazFirst.Add(udf)
			Next
			'	User usrMaz = Users.GetUserByEmail( Constants.WELCOME_MESSAGE_SENDER );
'
'			bool mazFound = false;
'			foreach ( DirectFriend udf in ufList )
'			{
'				if(( udf.Friend.ID == usrMaz.ID ))
'				{
'					usrDFWithMazFirst.Insert(0, udf);
'					mazFound = true;
'				}
'				else
'				{
'					usrDFWithMazFirst.Add(udf);
'				}
'			}
'			
'			if(mazFound)
'			{
'				if(usrDFWithMazFirst.Count>2)
'					usrDFWithMazFirst.Sort(1, usrDFWithMazFirst.Count-1, new BO.GenericSort("DateAdded","DESC"));
'			}
'			else
'				usrDFWithMazFirst.Sort(new BO.GenericSort("DateAdded","DESC"));
'

			txtFriendsCountHidden.Text = FriendsCount.ToString()
			endIndex = Math.Min(endIndex, FriendsCount)
			t = (endIndex - startIndex)
			Math.DivRem(t, Constants.MAX_PICTURES_ON_ROW, imagesOnLastRow)
			dgPager.dgListing.StartIndex = startIndex + 1
			dgPager.dgListing.EndIndex = endIndex
			dgPagerUp.dgListing.StartIndex = startIndex + 1
			dgPagerUp.dgListing.EndIndex = endIndex

			Select Case sSortBy
				Case Constants.FRIENDS_SORT_BY_GENDER
					DirectFriend.SortBy = Constants.FRIENDS_SORT_BY_GENDER
					Exit Select
				Case Constants.FRIENDS_SORT_BY_AGE
					DirectFriend.SortBy = Constants.FRIENDS_SORT_BY_AGE
					Exit Select
				Case Constants.FRIENDS_SORT_BY_MOST_RECENT
					DirectFriend.SortBy = Constants.FRIENDS_SORT_BY_MOST_RECENT
					Exit Select
				Case Constants.FRIENDS_SORT_BY_NAME
					DirectFriend.SortBy = Constants.FRIENDS_SORT_BY_NAME
					Exit Select
				Case Constants.FRIENDS_SORT_BY_ONLINE
					DirectFriend.SortBy = Constants.FRIENDS_SORT_BY_ONLINE
					Exit Select
			End Select

			usrDFWithMazFirst.Sort()

			For Each df As DirectFriend In usrDFWithMazFirst
				If counter >= startIndex AndAlso counter < endIndex Then
					dr = dt.NewRow()

					tmpUserPic = df.[Friend].DefaultPicture

					If tmpUserPic <> Nothing Then
						dr(0) = Pictures.GetPictureSrcFullURL(tmpUserPic, True, "../")
					Else
						dr(0) = "../images/default_thumbnail.gif"
					End If
					dr(1) = getBeginning(HttpUtility.HtmlEncode(df.[Friend].Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
					If LoggedUsersList.Contains(df.[Friend].ID) Then
						dr(2) = "../images/online_status.gif"
						'init according to the friend's online status
						dr(9) = Constants.ONLINE_STAUS_ON
					Else
						dr(2) = "../images/spacer.gif"
						dr(9) = Constants.ONLINE_STAUS_OFF
					End If
					If action = Constants.SEE_ALL_FRIENDS_EDIT_ACTION Then
						dr(3) = True
					Else
						dr(3) = False
					End If
					dr(4) = df.[Friend].ID

					dr(5) = "../" + Constants.MEMBERS + "?id=" + df.[Friend].ID
					dr(6) = "Delete"

					' sorting 
					dr(7) = df.[Friend].Gender
					dr(8) = df.DateAdded
					dr(10) = df.[Friend].BirthDay
					dr(11) = df.[Friend].Name
					dr(12) = 0

					dt.Rows.Add(dr)
				End If
				System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
			Next


			If imagesOnLastRow <> 0 Then
				blankImagesCount = Constants.MAX_PICTURES_ON_ROW - imagesOnLastRow
				Dim i As Integer = imagesOnLastRow
				While i < Constants.MAX_PICTURES_ON_ROW
					dr = dt.NewRow()
					'dr = dtTemp.NewRow();
					'dr[0] = "../images/empty_image.gif";
					dr(0) = "../images/spacer.gif"
					dr(1) = ""
					dr(2) = "../images/spacer.gif"
					dr(3) = "false"

					dr(4) = "-1"
					dr(5) = String.Empty
					dr(6) = String.Empty

					dr(7) = -1
					dr(8) = DateTime.MinValue
					dr(9) = -1
					dr(12) = -1
						'dtTemp.Rows.Add(dr);
					dt.Rows.Add(dr)
					System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
				End While
			End If

			'DataView dv = new DataView(dtTemp);
			Dim dv As New DataView(dt)
			'dv.Sort = sSortEx;
			Return dv
		End Function

		Public Sub Page_Load(ByVal Sender As Object, ByVal e As EventArgs)
			' this.pageTemplate.PageTitle = PageTitles.SEE_ALL_FRIENDS_PAGE;

			' Auto login from an external link
			'AutoLogin( Request );

			If LoggedUser = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Me.initPageTitles(Constants.SEE_ALL_FRIENDS, "", Form1, Nothing, htPageConstants)
			Me.initAdvertisements(Form1, Nothing)

			' init user whose friends to see: a member ot logged user
			dlAllFriends.RepeatColumns = Constants.MAX_PICTURES_ON_ROW
			Dim usr As User = Nothing
			If Request.Params("id") <> Nothing Then
				usrID = Convert.ToInt32(Request.Params("id"))
				usr = Users.GetUserByID(usrID)
			Else
				usrID = LoggedUser.ID
				usr = LoggedUser
			End If

			'init sort by param
			If (Request.Params(Constants.FRIENDS_SORT_BY_PARAM) <> Nothing) AndAlso (Request.Params(Constants.FRIENDS_SORT_BY_PARAM) <> "") Then
				sSortBy = Request.Params(Constants.GROUP_SORT_BY_PARAM)
			End If

			' check if the value is valid, if not - init woth default value: Most Recent
			If (sSortBy <> Constants.FRIENDS_SORT_BY_NAME) AndAlso (sSortBy <> Constants.FRIENDS_SORT_BY_MOST_RECENT) AndAlso (sSortBy <> Constants.FRIENDS_SORT_BY_ONLINE) AndAlso (sSortBy <> Constants.FRIENDS_SORT_BY_GENDER) AndAlso (sSortBy <> Constants.FRIENDS_SORT_BY_AGE) Then
				sSortBy = Constants.GROUP_SORT_BY_NAME
			End If

			' set add/edit friends visiblity
			If usrID <> LoggedUser.ID Then
				' if member
				imgAddFriends.Visible = False
				lbAddFriends.Visible = False
				imgEditFriends.Visible = False
				lbEditFriends.Visible = False

				ucMemberShortcut.UserID = usrID
			Else
				trUserShortCut.Visible = False
			End If

			Dim FriendsCount As Double = usr.DirectFriends.Count
			litFirstName.Text = usr.Name
			litFriendsCount.Text = FriendsCount.ToString()
			If FriendsCount = 0 Then
				tblFriends.Visible = False
				imgEditFriends.Visible = False
				lbEditFriends.Visible = False
				If Request.Params("id") <> Nothing AndAlso Request.Params("id") <> "" Then
					lblNoFriends.Text = Me.GetPageConstText(htPageConstants, "CONST_NoFriends_TEXT")
				End If
				lblNoFriends.Visible = True
			Else
				' init SortBy Links visibility, when sort functionality is added
				Select Case sSortBy
					Case Constants.FRIENDS_SORT_BY_GENDER
						lbNameSort.Visible = True
						lblNameSort.Visible = False
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbGender.Visible = False
						lblGender.Visible = True
						lbOnline.Visible = True
						lblOnline.Visible = False
						lbAge.Visible = True
						lblAge.Visible = False
						Exit Select
					Case Constants.FRIENDS_SORT_BY_ONLINE
						lbNameSort.Visible = True
						lblNameSort.Visible = False
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbGender.Visible = True
						lblGender.Visible = False
						lbOnline.Visible = False
						lblOnline.Visible = True
						lbAge.Visible = True
						lblAge.Visible = False
						Exit Select
					Case Constants.FRIENDS_SORT_BY_AGE
						lbNameSort.Visible = True
						lblNameSort.Visible = False
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbGender.Visible = True
						lblGender.Visible = False
						lbOnline.Visible = True
						lblOnline.Visible = False
						lbAge.Visible = False
						lblAge.Visible = True
						Exit Select
					Case Constants.FRIENDS_SORT_BY_MOST_RECENT
						lbNameSort.Visible = True
						lblNameSort.Visible = False
						lbMostRecent.Visible = False
						lblMostRecent.Visible = True
						lbGender.Visible = True
						lblGender.Visible = False
						lbOnline.Visible = True
						lblOnline.Visible = False
						lbAge.Visible = True
						lblAge.Visible = False
						Exit Select
					Case Constants.FRIENDS_SORT_BY_NAME
						lbNameSort.Visible = False
						lblNameSort.Visible = True
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbGender.Visible = True
						lblGender.Visible = False
						lbOnline.Visible = True
						lblOnline.Visible = False
						lbAge.Visible = True
						lblAge.Visible = False
						Exit Select
				End Select

				dgPager.RedirectPage = String.Format("{0}?id={1}&{2}={3}", Constants.SEE_ALL_FRIENDS, usrID, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				'Constants.SEE_ALL_FRIENDS + "?id=" + usrID;
				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(FriendsCount / Constants.MAX_PICTURES_ON_PAGE))
				dgPagerUp.RedirectPage = String.Format("{0}?id={1}&{2}={3}", Constants.SEE_ALL_FRIENDS, usrID, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				'Constants.SEE_ALL_FRIENDS + "?id=" + usrID;
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(FriendsCount / Constants.MAX_PICTURES_ON_PAGE))
				action = Request.Params("action")
				dgPager.Action = action
				dgPagerUp.Action = action
				If action = Constants.SEE_ALL_FRIENDS_EDIT_ACTION Then
					imgEditFriends.Visible = False
					lbEditFriends.Visible = False
				End If

				' initialize listing literals

				dgPager.dgListing.TotalCount = Convert.ToInt32(FriendsCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(FriendsCount)
				'dgListingUp.TotalCount = Convert.ToInt32(FriendsCount);

				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					txtStartIndexHidden.Text = "0"
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					txtStartIndexHidden.Text = Convert.ToString(((dgPager.CurrentPageNumber - 1) * Constants.MAX_PICTURES_ON_PAGE))
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)

				If Not IsPostBack Then
					BindList()
				End If
			End If


		End Sub

		Public Sub BindList()
			dlAllFriends.DataSource = CreateDataSource()
			dlAllFriends.DataBind()

			Dim itemsCount As Integer = dlAllFriends.Items.Count
			Dim blankImageIndex As Integer = itemsCount - blankImagesCount
			Dim i As Integer = 0
			i = blankImageIndex
			While i < itemsCount
				(DirectCast(dlAllFriends.Items(i).FindControl("hlName"), System.Web.UI.WebControls.HyperLink)).CssClass = "empty_image"
				(DirectCast(dlAllFriends.Items(i).FindControl("hlPhoto"), System.Web.UI.WebControls.HyperLink)).CssClass = "empty_image"
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
		End Sub

		Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
			Dim stringBuilder As New StringBuilder()
			Dim stringWriter As New StringWriter(stringBuilder)
			Dim htmlWriter As New HtmlTextWriter(stringWriter)
			MyBase.Render(htmlWriter)
			Dim html As String = stringBuilder.ToString()
			Dim start As Integer = html.IndexOf("<form name=""") + 12
			Dim [end] As Integer = html.IndexOf("""", start)
			Dim formID As String = html.Substring(start, [end] - start)
			Dim replace As String = formID.Replace(":", "_")
			html = html.Replace("document." + formID, "document." + replace)
			writer.Write(html)
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dlAllFriends.ItemCommand, AddressOf Me.dlAllFriends_ItemCommand

		End Sub
#End Region

		Private Sub dlAllFriends_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
			Dim src As Object = e.CommandSource
			Dim cmd As String = e.CommandName
			Dim arg As String = ""
			arg = (DirectCast(src, LinkButton)).CommandArgument

			Dim FriendItemID As Integer
			FriendItemID = Convert.ToInt32(arg)
			Dim usr As User = LoggedUser

			Select Case cmd
				Case "Delete"
					usr.RejectFriendship(Convert.ToInt32(arg))
					Exit Select
				Case "Unsubscribe"
					Response.Redirect(Constants.CONFIRM_UNSUBSCRIBE + "?" + Constants.GROUP_PARAM + "=" + FriendItemID)
					Exit Select
			End Select
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?action=" + Constants.SEE_ALL_FRIENDS_EDIT_ACTION)
		End Sub

		Protected Sub lbEditFriends_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?action=" + Constants.SEE_ALL_FRIENDS_EDIT_ACTION)
		End Sub

		Protected Sub lbAddFriends_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.INVITE_FRIENDS_PAGE)
		End Sub

		Protected Sub lbNameSort_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?id=" + usrID + "&" + Constants.FRIENDS_SORT_BY_NAME + "=" + Constants.GROUP_SORT_BY_NAME)
		End Sub

		Protected Sub lbMostRecent_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?id=" + usrID + "&" + Constants.FRIENDS_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_MOST_RECENT)
		End Sub

		Protected Sub lbGender_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?id=" + usrID + "&" + Constants.FRIENDS_SORT_BY_PARAM + "=" + Constants.FRIENDS_SORT_BY_GENDER)
		End Sub

		Protected Sub lbOnline_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?id=" + usrID + "&" + Constants.FRIENDS_SORT_BY_PARAM + "=" + Constants.FRIENDS_SORT_BY_ONLINE)
		End Sub

		Protected Sub lbAge_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.SEE_ALL_FRIENDS + "?id=" + usrID + "&" + Constants.FRIENDS_SORT_BY_PARAM + "=" + Constants.FRIENDS_SORT_BY_AGE)
		End Sub

		====================
		' This public property was added by conversion wizard to allow the access of a protected, autogenerated member variable Form1.
		====================
		Public ReadOnly Property Form1() As System.Web.UI.HtmlControls.HtmlForm
			Get
				Return Migrated_Form1
			End Get
		End Property
		'set { Migrated_Form1 = value; }
	End Class
End Namespace






